<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Qh_KnowledgeRequest;
use App\Jobs\QuestionDeleteHelperJob;
use App\Models\Qh_Course;
use App\Models\Qh_Knowledge;
use App\Models\Qh_LitQuestion;
use App\Models\Qh_Question;
use DB;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class Qh_KnowledgeController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = Qh_Knowledge::filter(\request()->all())
            ->with(['questionLibrary' => function($q) {
                $q->select(['id', 'name', 'province', 'amount', 'sort'])->orderByRaw('sort desc, id asc');
            }, 'course' => function($q) {
                $q->select(['id', 'name', 'sort'])->orderByRaw('sort desc, id asc');
            }, 'parent' => function($q) {
                $q->select(['id', 'name', 'sort'])->orderByRaw('sort desc, id asc');
            }])
            ->orderByRaw('sort desc, id asc')
            ->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Qh_KnowledgeRequest $request
     * @return JsonResponse|object
     * @throws Exception
     */
    public function store(Qh_KnowledgeRequest $request)
    {
        $params = $request->validated();

        if (empty($params['parentId'])) $params['level'] = 1;
        else $params['level'] = 2;

        if ($params['level'] == 1 && empty($params['courseId']))
            throw new Exception('请选择所属学科');

        if ($params['level'] == 2) {
            $parent = Qh_Knowledge::findOrFail($params['parentId']);
            $course = Qh_Course::findOrFail($parent->courseId);
        }else {
            $courseId = $params['courseId'];
            $course = Qh_Course::findOrFail($courseId);
        }

        $params['qlId'] = $course->qlId;
        $params['courseId'] = $course->id;

        $notice = Qh_Knowledge::create($params);

        return $this->restful($notice);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function show(int $id)
    {
        return $this->restful();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Qh_KnowledgeRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(Qh_KnowledgeRequest $request, int $id)
    {
        $params = $request->validated();

        $result = Qh_Knowledge::where('id', $id)->update($params);

        return $this->restful($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     * @throws Exception
     */
    public function destroy(int $id)
    {
        try {
            DB::transaction(function () use ($id) {
                $knowledge = Qh_Knowledge::findOrFail($id);

                // 试题数量更新
                updateQhQuestionCount($id, $knowledge->questionCount, 2);

                Qh_Knowledge::where('id', $id)->delete();

                // 删除子级
                Qh_Knowledge::where('parentId', $id)->delete();

                // 删除试题
                $questions = DB::table('qh_questions')->where('knowledgeId', $id)->get();
                foreach ($questions as $question) {
                    QuestionDeleteHelperJob::dispatch($question);
                }

                // 删除小题
                Qh_LitQuestion::where('knowledgeId', $id)->delete();
            });
        } catch (\Throwable $e) {
            throw new Exception("删除失败");
        }

        return $this->restful();
    }

    /**
     * 获取options
     * @return JsonResponse|object
     */
    public function getOptions() {
        $list = Qh_Knowledge::filter(\request()->all())->selectRaw('id as value, name as label, level')
            ->orderByRaw('sort desc, id asc')
            ->get();

        return $this->restful($list);
    }
}
